package com.example.demo.component;

import com.example.demo.util.FileUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author x c
 * @Email 378661553@qq.com
 * @Date Created in 2020/1/2 10:48
 */
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private byte[] body = new byte[0];

    public MyHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            setBody(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setBody(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        boolean ready = inputStream.isReady();// false
        boolean finished = inputStream.isFinished();// true
        if (!ready || finished) {
            return;
        }
        this.body = FileUtil.copyToByteArray(inputStream);
    }


    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(body)));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int readLine(byte[] b, int off, int len) throws IOException {
                return super.readLine(b, off, len);
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }
}
